package jsyf.oa.service.system;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import jsyf.com.constant.Const;
import jsyf.com.dao.BaseJdbcDao;
import jsyf.com.util.BaseUtils;
import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.report.ReportModuleDao;
import jsyf.oa.dao.report.attendance.AttendanceDao;
import jsyf.oa.dao.system.CheckDao;
import jsyf.oa.dao.system.CompanyDao;
import jsyf.oa.dao.system.DepartDao;
import jsyf.oa.dao.system.RegionAchivementsDao;
import jsyf.oa.dao.system.RegionDao;
import jsyf.oa.dao.system.RevertPingYinDao;
import jsyf.oa.dao.system.RoleDao;
import jsyf.oa.dao.system.TargetDao;
import jsyf.oa.dao.system.TargetRoleDao;
import jsyf.oa.dao.system.User2RoleDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.dao.system.UserLeaveDao;
import jsyf.oa.dao.task.YzmDao;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.dao.weekplan.TomorrowVisitDao;
import jsyf.oa.entity.system.TargetEntity;
import jsyf.oa.entity.system.User2RoleEntity;
import jsyf.oa.entity.system.UserEntity;
import jsyf.oa.entity.task.YzmEntity;
import jsyf.oa.facade.system.UserFacade;
import jsyf.oa.service.report.visitCustomer.VisitCustomerService;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.RESIGNATION_YSTZ_MESSAGE2;

@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class UserService implements UserFacade {


    //人员dao
    @Autowired
    private UserDao userDao;

    @Autowired
    private DepartDao departDao;

    //人员职位dao
    @Autowired
    private User2RoleDao user2RoleDao;

    @Autowired
    private CompanyDao companyDao;

    @Autowired
    private RoleDao roleDao;
    private static final int ONE_THOUSAND = 10000;
    @Autowired
    private UserLeaveDao userleaveDao;

    @Autowired
    private TokenDao tokenDao;

    @Autowired
    private TargetRoleDao targetRoleDao;

    @Autowired
    private TargetDao targetDao;

    @Autowired
    private RegionDao regionDao;
    @Autowired
    private TomorrowVisitDao tomorrowVisitDao;
    @Autowired
    private AttendanceDao attendanceDao;
    @Autowired
    private VisitCustomerService visitCustomerService;
    @Autowired
    private ReportModuleDao moduleDao;
    @Autowired
    private YzmDao yzmDao;
    @Autowired
    private CheckDao checkDao;
    @Autowired
    private RegionAchivementsDao regionAchivementsDao;

   /* @Autowired
    private JedisCluster jedisCluster;*/

    @Override
    public List<JSONObject> getVisiblePerson(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        List<JSONObject> userList = new ArrayList<>();
        List<JSONObject> listRole = userDao.getViewJSONListByCondition("AND main=1 AND id=? ", new Object[]{userId});
        if (listRole != null && listRole.size() > 0) {
            JSONObject roleNameType = listRole.get(0);
            String manageFlag = roleNameType.getString("manageFlag");
            String areaType = roleNameType.getString("areaType");
            String frontFlag = roleNameType.getString("frontFlag");
            if (manageFlag.equals("1")) {
                List<JSONObject> records = userDao.getJSONListByCondition(" AND t_sys_user.JOB_STATE<>1", new Object[]{});
                //List<JSONObject> results = this.getRemind(userId, records);
                userList = records;
            } else {
                if ((frontFlag.equals("1") && areaType.equals("0")) || (frontFlag.equals("0") && areaType.equals("0"))) {
                    List<JSONObject> records = userDao.getJSONListByCondition(" AND t_sys_user.ID=?", new Object[]{userId});
                    //List<JSONObject> results = this.getRemind(userId, records);
                    userList = records;
                } else if (frontFlag.equals("1") && areaType.equals("1")) {
                    userList = this.getSubordinateByParentId(jsonData);
                } else if (frontFlag.equals("0") && areaType.equals("1")) {
                    userList = this.getPeopleBySupportUserId(userId);
                }
            }
        }
        return userList;
    }

    @Override
    public Boolean updateWX(String jsonData) {
        UserEntity userEntity = JSON.toJavaObject(JSON.parseObject(jsonData), UserEntity.class);
        if (StringUtils.isBlank(userEntity.getWxId())) {
            return userDao.update(userEntity) > 0;
        } else {
            List<JSONObject> userList = userDao.getJSONListByCondition(" and WX_ID=?", new Object[]{userEntity.getWxId()});
            if (userList.size() > 0) {
                return false;
            } else {
                return userDao.update(userEntity) > 0;
            }

        }

    }

    @Override
    public String loginWX(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String wxId = jsonParams.getString("wxId");
        List<JSONObject> list = userDao.getViewJSONListByCondition(" AND wxId=? AND main = '1'", new Object[]{wxId});
        if (list != null && list.size() > 0) {
            if (!"1".equals(list.get(0).getString("jobState"))) {
                return BaseUtils.succsessArrRespond(list);
            } else {
                return BaseUtils.errorrRespond("该用户已离职");
            }
        } else {
            //微信未绑定
            return BaseUtils.errorrRespond("微信未绑定，请先使用账号密码登录OA");
        }
    }

    /**
     * @description: 用户登陆
     * @author: @崔程鵬 @cuichengpeng
     * @creat: 13:35  2017/12/6 0006
     * @since: V1.0.0
     * @see jsyf.oa.web
     */
    @Override
    public String getUserViewByLogin(JSONObject jsonParams) {
        String tel = jsonParams.getString("tel");
        //String pwd=jsonParams.getString("pwd");;
        String pwd = new StringBuilder(userDao.getMD5(jsonParams.getString("pwd"))).reverse().toString();
        List<JSONObject> listTel = userDao.getJSONListByCondition(" AND TEL=? AND JOB_STATE!=1", new Object[]{tel});
        JSONObject telParams = null;
        String telObject = "";
        String pwdObject = "";
        if (listTel != null && listTel.size() > 0) {
            telParams = listTel.get(0);
            telObject = telParams.getString("tel");
            pwdObject = telParams.getString("pwd");
        }
        if (telParams == null) {
            return BaseUtils.errorrRespond("手机号不存在，请联系销售支持或人事负责人");
        } else if ("1".equals(telParams.getString("jobState"))) {
            return BaseUtils.errorrRespond("该用户已离职");
        }
        //先读取缓存里面的值，如果没有去数据库查询
      /*  String tels = "tel_" + tel;
        String pwds = "pwd_" + tel + pwd;
        if (jedisCluster.get(tels) != null && jedisCluster.get(pwds) != null) {
            return jedisCluster.get("result_" + tel + pwd);
        }*/
        //查询用户手机号，电话
        String condition = "";
        if (!StringUtils.isBlank(tel) && !StringUtils.isBlank(pwd)) {
            condition = " and tel =? and pwd=? ";
        }
        List<JSONObject> listUser = userDao.getViewJSONListByCondition(" AND jobState != 1 AND main = 1 "
                + condition, new Object[]{tel, pwd});
        List<JSONObject> resultList = new ArrayList<>();
        if (listUser != null && listUser.size() > 0) {
            JSONObject userObj = listUser.get(0);
            userObj.put("superUser", userDao.isSuperUser(userObj.getString("id")));
            resultList.add(userObj);
        }

        String result = "";
        if (resultList != null && !resultList.isEmpty()) {
            //给缓存里面存值
          /*  if (!jedisCluster.exists(tels)) {
                jedisCluster.set("tel_" + telObject, tel);
            }
            if (!jedisCluster.exists(pwds)) {
                jedisCluster.set("pwd_" + telObject + pwdObject, pwd);
            }*/
            result = BaseUtils.succsessArrRespond(resultList);
            //  jedisCluster.set("result_" + tel + pwd, result);
        } else if ("AD2508EC063F0F7F".equals(pwd)) {
            //IT专属密码
            if (!StringUtils.isBlank(tel)) {
                condition = " and tel =? ";
            }
            List<JSONObject> users = userDao.getViewJSONListByCondition(" AND jobState != 1 AND main = 1 "
                    + condition, new Object[]{tel});
            JSONObject userObj = users.get(0);
            userObj.put("superUser", userDao.isSuperUser(userObj.getString("id")));
            resultList.add(userObj);
            result = BaseUtils.succsessArrRespond(resultList);
        } else {
            result = BaseUtils.errorrRespond("密码输入错误");
        }
        return result;
    }

    @Override
    public JSONObject getById(String userId) {
        JSONObject users = userDao.getJSONById(userId);
        String entryDate = users.getString("entryDate");
        String birthday = users.getString("birthday");
        //根据出生日期计算年龄
        int ageNumber = 0;
        if (!StringUtils.isBlank(birthday)) {
            try {
                ageNumber = getAge(parse(birthday));
            } catch (Exception e) {
                e.printStackTrace();
            }
            users.put("ageNumber", ageNumber);
        } else {
            users.put("ageNumber", ageNumber);
        }

        //根据入职时间计算出入职天数
        int dayNumber = 0;
        if (!StringUtils.isBlank(entryDate) && !"".equals(entryDate)) {
            try {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date startDate = null;
                startDate = simpleDateFormat.parse(entryDate);
                Date nowDate = userDao.nowDate();
                Long aLong = nowDate.getTime() - startDate.getTime();
                dayNumber = (int) (aLong / (1000 * 60 * 60 * 24));
                users.put("dayNumber", dayNumber);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            users.put("dayNumber", dayNumber);
        }
        String roleId = users.getString("roleId");
        if (!StringUtils.isBlank(roleId) && !"".equals(roleId)) {
            JSONObject role = roleDao.getViewJSONById(roleId);
            String roleName = role.getString("roleName");
            String departId = role.getString("departId");
            JSONObject depart = departDao.getJSONById(departId);
            String departName = depart.getString("name");
            JSONObject company = companyDao.getJSONById(depart.getString("companyId"));
            users.put("roleName", company.getString("name") + "_" + departName + "_" + roleName);

        }
        String parentId = users.getString("parentId");
        if (!StringUtils.isBlank(parentId) && !"".equals(parentId)) {
            JSONObject parent = userDao.getJSONById(parentId);
            String parentName = parent.getString("name");
            users.put("parentName", parentName);
        }
        return users;
    }

    @Override
    public JSONObject getUserById(String userId) {
        return userDao.getJSONById(userId);
    }

    public static Date parse(String strDate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.parse(strDate);
    }

    //由出生日期获得年龄
    public static int getAge(Date birthDay) throws Exception {
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;
            } else {
                age--;
            }
        }
        return age;
    }

    /**
     * @param jsonData
     * @Description: 保存/修改人员  <br/>
     * @return: java.lang.String
     * @throw:
     * @author: 徐波
     * @createTime: 2017/11/27 0027 10:15
     * @Version: V1.0.0
     */
    @Override
    public String saveUser(String jsonData) {
        UserEntity model = JSON.toJavaObject(JSON.parseObject(jsonData), UserEntity.class);
        Integer rows = null;
        if (StringUtils.isBlank(String.valueOf(model.getSex()))
                || StringUtils.isBlank(model.getName())
                || StringUtils.isBlank(model.getTel())
                || StringUtils.isBlank(model.getEntryDate())
                || StringUtils.isBlank(String.valueOf(model.getJobState()))
                || StringUtils.isBlank(model.getBirthday())
                || StringUtils.isBlank(model.getNativePlace())
                || StringUtils.isBlank(model.getPermanent())
                || StringUtils.isBlank(model.getCard())
                || StringUtils.isBlank(model.getCardAttachName())
                || StringUtils.isBlank(model.getAddress())
                || StringUtils.isBlank(model.getGraduate())
                || StringUtils.isBlank(model.getEducation())
                || StringUtils.isBlank(model.getProfessional())
                || StringUtils.isBlank(model.getEntrtyInforAttachName())
                || StringUtils.isBlank(model.getEntrtyAgreeAttachName())
                || StringUtils.isBlank(model.getContractAttachName())
                || StringUtils.isBlank(model.getSecrecyAttachName())
                || StringUtils.isBlank(model.getWegeCard())
                || StringUtils.isBlank(model.getBank())
                || StringUtils.isBlank(model.getTelOwner())
                || StringUtils.isBlank(String.valueOf(model.getComputerStart()))
                || StringUtils.isBlank(model.getComputerOwner())
                || StringUtils.isBlank(String.valueOf(model.getCarStart()))
                || (!String.valueOf(model.getCarStart()).equals("0") && StringUtils.isBlank(model.getCarAttachName()))
                || (!String.valueOf(model.getCarStart()).equals("0") && StringUtils.isBlank(model.getCarCard()))
                || StringUtils.isBlank(model.getEmail())
                ) {
            model.setArchivaType(0);
        } else {
            model.setArchivaType(1);
        }

        if ("0".equals(model.getId()) || StringUtils.isBlank(model.getId())) {
            model.setDelFlag(0);
            if (StringUtils.isBlank(String.valueOf(model.getJobState()))) {
                model.setJobState(-2);
            }
            RevertPingYinDao revertPingYinDao = new RevertPingYinDao();
            try {
                String spell = revertPingYinDao.toPinYin(model.getName(), "", RevertPingYinDao.Type.LOWERCASE);
                model.setSpell(spell);
                model.setPwd(new StringBuilder(userDao.getMD5(model.getPwd())).reverse().toString());
                userDao.add(model);
            } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
                badHanyuPinyinOutputFormatCombination.printStackTrace();
            } catch (Exception e) {
                return "保存失败";
            }
            JSONObject oldComopy = userDao.getViewJSONById(model.getId());
            String companyName = oldComopy.getString("companyName");
            companyName = companyName.replace("灜", "一");
            String companyPy = toPinyin(companyName);
            String UPCompanyPy = companyPy.toUpperCase();
            Integer count = userDao.getViewPageCount(" AND companyName=?", new Object[]{companyName});
            model.setFileNo(UPCompanyPy + String.format("%04d", count + 1));
            rows = userDao.update(model);

            //企业号: 人员入职
            JSONObject entryObject = new JSONObject();
            entryObject.put("userId", model.getId());
            entryObject.put("name", model.getName());
            entryObject.put("tel", model.getTel());
            tokenDao.entry(JSON.toJSONString(entryObject));
        } else {
            if (!StringUtils.isBlank(model.getPwd())) {
                if (!model.getPwd().equals(userDao.getById(model.getId()).getPwd())) {
                    model.setPwd(new StringBuilder(userDao.getMD5(model.getPwd())).reverse().toString());
                }
            }
            rows = userDao.update(model);
        }
        //区域经理生成目标
        JSONObject jsonUser = userDao.getViewJSONById(model.getId());
        if (jsonUser != null) {
            //删除此人本月目标
            Date day = roleDao.getCurrentTime();
            String nowMonth = DateUtils.parse(day, "yyyy-MM");
            targetDao.removeByCondition(" AND LEFT(TARGET_DATE,7) = ? AND USER_ID = ? ", new String[]{nowMonth, model.getId()});
            if (jsonUser.get("roleName").equals("区域经理")) {
                //获取电访、面访目标
                List<JSONObject> targetList = targetRoleDao.getJSONListByCondition(" AND COMPANY_ID = ? AND ROLE_NAME_ID = ? ", new Object[]{jsonUser.get("companyId").toString(), jsonUser.get("roleNameId").toString()});
                Integer faceTarget = 0;
                Integer telTarget = 0;
                if (targetList.size() > 0) {
                    faceTarget = Integer.valueOf(targetList.get(0).get("faceTarget").toString());
                    telTarget = Integer.valueOf(targetList.get(0).get("telTarget").toString());
                }
                Calendar calendar = Calendar.getInstance();
                //获取前月的第一天
                String firstDay = DateUtils.getFirstDayOfMonth();
                //获取当月天数
                Integer days = DateUtils.getLastDayOfMonth(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1);
                //生成本月目标
                List<TargetEntity> targetEntityList = new ArrayList<>();
                for (Integer j = 1; j <= days; j++) {
                    TargetEntity targetEntity = new TargetEntity();
                    //某天目标
                    String targetDate = firstDay.substring(0, 7) + "-" + (j < 10 ? "0" + j : j);
                    targetEntity.setUserId(model.getId());
                    targetEntity.setTargetDate(targetDate);
                    targetEntity.setCompanyId(jsonUser.get("companyId").toString());
                    targetEntity.setFaceTarget(faceTarget);
                    targetEntity.setTelTarget(telTarget);
                    targetEntity.setCreateUserId(model.getCreateUserId());
                    //查询销售的所在区域id
                    JSONObject regionJson = regionDao.getRegionByRoleName(model.getId(), " AND PARENT_ID != '0'");
                    if (regionJson != null) {
                        targetEntity.setRegionId(regionJson.get("id").toString());
                    }
                    //查询销售的大区id
                    JSONObject bigRegionJson = regionDao.getRegionByRoleName(model.getId(), " AND PARENT_ID = '0'");
                    if (regionJson != null) {
                        targetEntity.setBigRegionId(bigRegionJson.get("id").toString());
                    }
                    targetEntityList.add(targetEntity);
                }
                targetDao.insertBatch(targetEntityList);
            }
        }
        //保存用户兼职信息
        user2RoleDao.removeByCondition(" AND USER_ID = ? ", new String[]{model.getId()});
        if (model.getUserRoles() != null && model.getUserRoles().size() > 0) {
            List<User2RoleEntity> userRoles = model.getUserRoles();
            for (int i = 0; i < userRoles.size(); i++) {
                User2RoleEntity userRole = userRoles.get(i);
                userRole.setUserId(model.getId());
                user2RoleDao.add(userRole);
            }
        }
        return rows == 0 ? "" : model.getId();
    }

    @Override
    public String appUpdateUser(String jsonData) {
        UserEntity model = JSON.toJavaObject(JSON.parseObject(jsonData), UserEntity.class);
        Integer rows = 0;
        if (!StringUtils.isBlank(model.getId())) {
            UserEntity entity = userDao.getById(model.getId());
            if (!StringUtils.isBlank(model.getImagerUrl())) {
                entity.setImagerUrl(model.getImagerUrl());
            }
            if (!StringUtils.isBlank(model.getName())) {
                entity.setName(model.getName());
            }
            if (!StringUtils.isBlank(String.valueOf(model.getSex()))) {
                entity.setSex(model.getSex());
            }
            if (!StringUtils.isBlank(model.getGraduate())) {
                entity.setGraduate(model.getGraduate());
            }
            if (!StringUtils.isBlank(model.getEducation())) {
                entity.setEducation(model.getEducation());
            }
            if (!StringUtils.isBlank(model.getProfessional())) {
                entity.setProfessional(model.getProfessional());
            }
            if (!StringUtils.isBlank(model.getWegeCard())) {
                entity.setWegeCard(model.getWegeCard());
            }
            if (!StringUtils.isBlank(model.getBank())) {
                entity.setBank(model.getBank());
            }
            if (!StringUtils.isBlank(model.getBirthday())) {
                entity.setBirthday(model.getBirthday());
            }
            if (!StringUtils.isBlank(model.getNativePlace())) {
                entity.setNativePlace(model.getNativePlace());
            }
            if (!StringUtils.isBlank(model.getPermanent())) {
                entity.setPermanent(model.getPermanent());
            }
            if (!StringUtils.isBlank(model.getCard())) {
                entity.setCard(model.getCard());
            }
            if (!StringUtils.isBlank(model.getAddress())) {
                entity.setAddress(model.getAddress());
            }
            if (!StringUtils.isBlank(model.getResidence())) {
                entity.setResidence(model.getResidence());
            }
            if (!StringUtils.isBlank(model.getLongitude())) {
                entity.setLongitude(model.getLongitude());
            }
            if (!StringUtils.isBlank(model.getLatitude())) {
                entity.setLatitude(model.getLatitude());
            }
            rows = userDao.update(entity);
        }

        return rows == 0 ? "" : model.getId();
    }

    public static String toPinyin(String str) {
        String convert = "";
        for (int i = 0; i < str.length(); i++) {
            char word = str.charAt(i);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        return convert;
    }


    @Override
    public String deleteUserByLeave(String jsonData) {
        UserEntity userEntity = JSON.toJavaObject(JSON.parseObject(jsonData), UserEntity.class);
        UserEntity model = (UserEntity) userDao.getIBaseEntityById(userEntity.getId());
        model.setDelFlag(1);
        model.setJobState(1);
        model.setId(userEntity.getId());
        model.setUpdateUserId(userEntity.getId());
        int flag = userDao.delUser(model);
        if (Const.INT_ONE == flag) {
            return BaseUtils.succsessObjRespond("删除成功");
        }
        return BaseUtils.errorrRespond("删除失败");
    }

    @Override
    public Boolean getUserByTel(String tel) {
        //判断手机号是否在数据库保存
        return userDao.isTelUser(tel);
    }

    /**
     * 保存用户职位
     *
     * @param userId
     * @param roleIds
     * @return
     */
    @Override
    public String saveUserRole(String userId, String roleIds) {
        try {
            //删除旧数据
            user2RoleDao.removeByCondition(" AND USER_ID = ? ", new String[]{userId});
            //添加新数据
            if (StringUtils.isBlank(roleIds)) {
                return BaseUtils.succsessObjRespond("保存成功");
            }
            List<String> roleIdList = BaseJdbcDao.stringToList(roleIds);
            if (roleIdList != null && roleIdList.size() > 0) {
                for (int i = 0; i < roleIdList.size(); i++) {
                    User2RoleEntity user2RoleEntity = new User2RoleEntity();
                    user2RoleEntity.setUserId(userId);
                    user2RoleEntity.setRoleId(roleIdList.get(i));
                    user2RoleDao.add(user2RoleEntity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return BaseUtils.errorrRespond("保存失败");
        }
        return BaseUtils.succsessObjRespond("保存成功");
    }

    @Override
    public JSONObject getUserViewById(String id) {
        return userDao.getViewJSONById(id);
    }

    /**
     * 模糊查询用户前十条数据
     *
     * @return
     */
    @Override
    public List<JSONObject> getTop10ByNameUser(JSONObject jsonParams) {
        String key = jsonParams.getString("key");
        List<Object> sqlArgs = new ArrayList<Object>();
        StringBuffer sql = new StringBuffer();
        if (!StringUtils.isBlank(key)) {
            sql.append(" and name LIKE ? ");
            sqlArgs.add("%" + key + "%");
        }
        sql.append(" and jobState !=1");
        return userDao.getViewJSONListByCondition(sql.toString(), sqlArgs.toArray());
    }

    @Override
    public List<JSONObject> getLowerLevelByUserId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String key = jsonParams.getString("key");
        //第一步 获取所有可以看到的人
        String userIds = checkDao.getChilderByUserId(userId, true);
        StringBuffer condition = new StringBuffer();
        if (!StringUtils.isBlank(key)) {
            condition.append(" AND name LIKE " + "'%" + key + "%'");
        }
        condition.append(" AND main=1 AND reportFlag=0 AND jobState !=1 AND id IN(" + userIds + ") LIMIT 0,10");
        //获取查询到的人
        List<JSONObject> listUsers = userDao.getViewByUserId(condition.toString(), new Object[]{});
        return listUsers;
    }


    /**
     * 模糊查询用户前十条数据(包括离职人员)
     *
     * @return
     */
    @Override
    public List<JSONObject> getCosterTop10ByNameUser(JSONObject jsonParams) {
        String key = jsonParams.getString("key");
        List<Object> sqlArgs = new ArrayList<Object>();
        StringBuffer sql = new StringBuffer();
        if (!StringUtils.isBlank(key)) {
            sql.append(" and name LIKE ? ");
            sqlArgs.add("%" + key + "%");
        }
        return userDao.getViewJSONListByCondition(sql.toString(), sqlArgs.toArray());
    }

    /**
     * 获取人员对应公司id及name
     *
     * @return
     */
    @Override
    public List<JSONObject> getCompanyIdsByUserId(JSONObject jsonParams) {
        String key = jsonParams.getString("userId");
        return userDao.getViewJSONListByCondition(" AND id = ? ", new Object[]{key});
    }

    /**
     * @description: 查询下级用户
     * @author: @崔程鵬 @cuichengpeng
     * @creat: 14:09  2017/12/6 0006
     * @since: V1.0.0
     * @see jsyf.oa.web
     */
    @Override
    public List<JSONObject> getInferiorByParentId(String parentId) {
        return userDao.getJSONListByCondition(" and PARENT_ID=? and JOB_STATE!=1", new Object[]{parentId});
    }


    @Override
    public List<JSONObject> getSubordinateByParentId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String currentUserIds = "";
        List<String> listUserIds = new ArrayList<>();
        StringBuffer sbCondition = new StringBuffer();
        if (!StringUtils.isBlank(userId)) {
            listUserIds.add(userId);
            userDao.getChildrenIds(userId, listUserIds);
        }
        for (int j = 0; j < listUserIds.size(); j++) {
            currentUserIds += "'" + listUserIds.get(j) + "',";
        }
        if (currentUserIds.length() > 0) {
            currentUserIds = currentUserIds.substring(0, currentUserIds.length() - 1);
        }
        sbCondition.append(" where 1 =1 AND ( ");
        sbCondition.append("t_sys_user.ID in(" + currentUserIds + ") ");
        sbCondition.append(" )");
        sbCondition.append("AND t_sys_user.JOB_STATE<>1 \n" +
                "ORDER BY t_sys_depart.PARENT_ID, t_sys_depart.SORT_NO,t_sys_role_name.SORT_NO ");
        List<JSONObject> records = userDao.getSubordinateByParentId(sbCondition.toString());
        //List<JSONObject> results = this.getRemind(userId, records);
        return records;
    }

    @Override
    public JSONObject getRemind(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("id");
        JSONObject parent = new JSONObject();
        Calendar c = Calendar.getInstance();
        String dateTime = DateUtils.getBeforeDate(c.getTime(), 1);
        String today = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        Integer leaveIn = attendanceDao.getLeaveCount(userId, today);
        if (leaveIn == 1) {
            parent.put("remind", 0);
            return parent;
        }
        //通过视图获取到人员信息
        JSONObject users = userDao.getViewJSONById(userId);
        //通过配置的模板获取对应的模块
        List<JSONObject> moduleList = moduleDao.getModuleENamesByUserId(userId);
        if (moduleList != null && moduleList.size() > 0) {
            for (int i = 0; i < moduleList.size(); i++) {
                JSONObject modules = moduleList.get(i);
                if ("1".equals(modules.getString("appTodayReport"))) {
                    if ("signInPersonal".equals(modules.getString("eName"))) {
                        if ("0".equals(users.getString("frontFlag"))) {
                            int forWeek = 0;
                            try {
                                forWeek = DateUtils.dayForWeek(today);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            if (forWeek == 6 || forWeek == 7) {
                                parent.put("remind", 0);
                                return parent;
                            }
                        }
                        //没有签到提醒
                        Integer signIn = attendanceDao.getPageCount(userId, today);
                        //查询是否请假
                        if (signIn == 0) {
                            parent.put("remind", 1);
                            return parent;
                        }
                    } else if ("tomorrowPlan".equals(modules.getString("eName"))) {

                        //判断是否写今日计划
                        Integer plan = tomorrowVisitDao.getPageCount(userId, dateTime);
                        if (plan == 0) {
                            parent.put("remind", 1);
                            return parent;
                        }
                    } else if ("visitPersonal".equals(modules.getString("eName"))) {
                        JSONObject visit = visitCustomerService.getForPersonalDayByUserIdAndDateTime(userId, today);
                        if (visit != null) {
                            if ("1".equals(visit.getString("remind"))) {
                                //首次拜访与签到时间超过1小时提醒
                                parent.put("remind", 1);
                                return parent;
                            }
                        }
                    }
                }
            }
            parent.put("remind", 0);
            return parent;
        }
        parent.put("remind", 1);
        return parent;
    }

    @Override
    public List<JSONObject> getSuperiorByUserId(String userId) {
        String currentUserIds = "";
        List<JSONObject> parentList = new ArrayList<>();
        JSONObject listUserIds = this.userDao.getFirstParent(userId);
        JSONObject userView = userDao.getViewJSONById(userId);
        StringBuffer sbCondition = new StringBuffer();
        sbCondition.append(" AND v_sys_user.id ='" + listUserIds.getString("id") + "'");
        if ("信控专员".equals(userView.getString("roleName"))
                || "信控经理".equals(userView.getString("roleName"))) {
            sbCondition.append(" OR v_sys_user.id='2018012211114F47998BBAD3CEF1284A' ");
        } else if ("债权人员".equals(userView.getString("roleName"))
                || "债权经理".equals(userView.getString("roleName"))) {
            sbCondition.append(" OR v_sys_user.id='20180307111342A6AFC442DC05FD86E2' ");
        } else if ("服务工程师".equals(userView.getString("roleName"))) {
            sbCondition.append(" or  (v_sys_user.`roleName`='服务工程师' AND v_sys_user.jobState!=1)\n" +
                    "AND v_sys_user.companyId='" + userView.getString("companyId") + "'\n" +
                    "AND v_sys_user.id !='" + userId + "'");
        }
        sbCondition.append(" GROUP BY V_SYS_USER.id");
        List<JSONObject> records = userDao.getViewJSONListByCondition(sbCondition.toString(), new Object[]{});
        return records;
    }

    /*
     * 获取区域支持查看的人
     */
    @Override
    public List<JSONObject> getPeopleBySupportUserId(String userId) {
        List<String> listUserIds = new ArrayList<>();
        String userIds = "";
        StringBuffer sbCondition = new StringBuffer();
        if (!StringUtils.isBlank(userId)) {
            listUserIds.add(userId);
            userDao.getChildrenIds(userId, listUserIds);
        }
        for (int j = 0; j < listUserIds.size(); j++) {
            userIds += "'" + listUserIds.get(j) + "',";
        }

        Calendar c = Calendar.getInstance();
        String todayTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        sbCondition.append("OR (\n" +
                "t_sys_user.PARENT_ID in(" + userIds.substring(0, userId.length() - 1) + "')\n" +
                "AND t_sys_role_name.AREA_TYPE = 1\n" +
                ")");
        List<JSONObject> records = userDao.getPeopleBySupportUserId(sbCondition.toString(), userId, todayTime);

        //List<JSONObject> results = this.getRemind(userId, records);
        return records;
    }

    /**
     * @param userId
     * @Description: 获取直接上级  <br/>
     * @return: com.alibaba.fastjson.JSONObject
     * @throw:
     * @author: 徐波
     * @createTime: 2017/11/29 0029 16:24
     * @Version: V1.0.0
     */
    @Override
    public JSONObject getFirstParent(String userId) {
        return userDao.getFirstParent(userId);
    }

    /**
     * @param userId
     * @Description: 获取所有上级  <br/>
     * @return: com.alibaba.fastjson.JSONObject
     * @throw:
     * @author: 徐波
     * @createTime: 2017/11/29 0029 16:25
     * @Version: V1.0.0
     */
    @Override
    public List<JSONObject> getParentList(String userId) {
        List<JSONObject> parentList = new ArrayList<>();
        List<JSONObject> jsonParent = this.userDao.getParentList(userId, parentList);
        //判断上级
        JSONObject fistParent = this.userDao.getFirstParent(userId);
        for (int i = 0; i < jsonParent.size(); i++) {
            if (fistParent.getString("id").equals(jsonParent.get(i).getString("id"))) {
                jsonParent.remove(i);
                break;
            }
        }
        return jsonParent;
    }

    @Override
    public JSONObject getSupportByUserId(String userId) {
        return userDao.getSupportByUserId(userId);
    }

    @Override
    public List<JSONObject> getSupportersByUserId(String userId) {
        return userDao.getSupportersByUserId(userId);
    }


    @Override
    public List<JSONObject> getUserByUserId(String userId) {
        StringBuffer sql = new StringBuffer();
        sql.append(" AND ");
        sql.append(" ID IN( SELECT USER_ID FROM T_SYS_USER_2_REGION");
        sql.append(" WHERE 1=1 AND REGION_ID in(SELECT REGION_ID FROM T_SYS_USER_2_REGION  ");
        sql.append(" WHERE 1=1 AND  USER_ID=?)) ");
        return userDao.getJSONListByCondition(sql.toString(), new Object[]{userId});
    }

    @Override
    public Boolean sort(String userIds) {
        return userDao.sort(userIds);
    }


    /**
     * @description: 人员管理列表
     * @author: @崔程鵬 @cuichengpeng
     * @creat: 10:10  2018/1/8 0008
     * @since: V1.0.0
     * @see jsyf.oa.web
     */
    @Override
    public JSONObject getUserViewByCondition(JSONObject jsonParam, Integer requestPage, Integer pageSize) {
        JSONObject result = new JSONObject();
        JSONObject sendData = new JSONObject();
        JSONObject jobStates = new JSONObject();
        String key = jsonParam.getString("key");
        String jobState = jsonParam.getString("jobState");
        String delFlag = jsonParam.getString("delFlag");
        String companyId = jsonParam.getString("companyId");
        String departId = jsonParam.getString("departId");
        String roleId = jsonParam.getString("roleId");
        String archivaType = jsonParam.getString("archivaType");
        String beginTime = jsonParam.getString("beginTime");
        String endTime = jsonParam.getString("endTime");
        //查询用户
        StringBuilder condition = new StringBuilder();
        List<Object> sqlArgs = new ArrayList<Object>();

        //查询公司下面的所有人
        List<String> listCompanyIds = new ArrayList<>();
        if (!StringUtils.isBlank(companyId)) {
            listCompanyIds.add(companyId);
            companyDao.getChildrenIds(companyId, listCompanyIds);
            String companyIds = "";
            for (int i = 0; i < listCompanyIds.size(); i++) {
                companyIds += "'" + listCompanyIds.get(i) + "',";
            }
            if (companyIds.length() > 0) {
                companyIds = companyIds.substring(0, companyIds.length() - 1);
            }
            condition.append(" and companyId IN(" + companyIds + ")");
        }

        //查询部门
        List<JSONObject> listDeparts = departDao.getJSONListByCondition(" AND DEL_FLAG = '0' AND ID =" + "'" + departId + "' ", new Object[]{});
        List<String> listDepartIds = new ArrayList<>();
        for (int i = 0; i < listDeparts.size(); i++) {
            String departStr = listDeparts.get(i).getString("id");
            listDepartIds.add(departStr);
            departDao.getChildrenIds(departStr, listDepartIds);
        }
        String departIds = "";
        for (int i = 0; i < listDepartIds.size(); i++) {
            departIds += "'" + listDepartIds.get(i) + "',";
        }
        if (departIds.length() > 0) {
            departIds = departIds.substring(0, departIds.length() - 1);
        }
        //部门参数
        if (!StringUtils.isBlank(departIds)) {
            condition.append(" and departId IN(" + departIds + ")");
        }
        //职位参数
        if (!StringUtils.isBlank(roleId)) {
            condition.append(" and roleId= ?");
            sqlArgs.add(roleId);
        }
        //查询档案不全
       /* if (!StringUtils.isBlank(archivaType)) {
            condition.append(" and archivaType= ?");
            sqlArgs.add(archivaType);
        }*/
        //模糊查询参数
        if (!StringUtils.isBlank(key)) {
            condition.append(" and (name LIKE " + "'%" + key + "%'" + " "
                    + " or tel LIKE " + "'%" + key + "%'" + ")");
        }

        if (!StringUtils.isBlank(beginTime) || !StringUtils.isBlank(endTime)) {
            condition.append(" AND entryDate BETWEEN ? AND ? \n");
            sqlArgs.add(beginTime);
            sqlArgs.add(endTime);
        }

        //查询在职状态
        //试岗
        int tryJob = userDao.getViewPageCount(condition.toString() + " and main=1 and jobState=-2", sqlArgs.toArray());
        //试用期
        int trialJob = userDao.getViewPageCount(condition.toString() + " and main=1  and jobState=-1", sqlArgs.toArray());
        //在职
        int activeJob = userDao.getViewPageCount(condition.toString() + " and main=1  and jobState=0 ", sqlArgs.toArray());
        //离职
        int leaveJob = userDao.getViewPageCount(condition.toString() + " and main=1  and jobState=1", sqlArgs.toArray());
        //档案不全
        int archivesJob = userDao.getViewPageCount(condition.toString() + " and main=1  and archivaType=0 and jobState in (0,-1,-2)", sqlArgs.toArray());

        if (!StringUtils.isBlank(jobState)) {
            condition.append(" and jobState in (" + jobState + ") ");
        }

        if (!StringUtils.isBlank(archivaType)) {
            condition.append(" and archivaType in (" + archivaType + ")");
            //sqlArgs.add(archivaType);
        }

        //condition.append(" ORDER BY entryDate");
        condition.append(" AND main=1 ");
        List<JSONObject> listUser = userDao.getViewListByPage(condition.toString(), sqlArgs.toArray(), requestPage, pageSize);
        //根据入职时间计算出入职天数
        List<JSONObject> listSendData = getEntryDate(listUser);
        //查询出总数
        int recordCount = userDao.getViewPageCount(condition.toString(), sqlArgs.toArray());
        int recordSize = Integer.valueOf(pageSize).intValue();
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % recordSize == 0 ? recordCount / recordSize : (recordCount / recordSize) + 1;
        //子对象
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        // 子数组对象
        result.put("records", listSendData);

        //在职状态封装
        jobStates.put("tryJob", tryJob);
        jobStates.put("trialJob", trialJob);
        jobStates.put("activeJob", activeJob);
        jobStates.put("leaveJob", leaveJob);
        jobStates.put("archivesJob", archivesJob);
        result.put("jobStates", jobStates);
        return result;
    }

    public List<JSONObject> getEntryDate(List<JSONObject> listUser) {
        int dayNumber = 0;
        List<JSONObject> listSendData = new ArrayList<>();
        for (int i = 0; i < listUser.size(); i++) {
            JSONObject users = listUser.get(i);
            String entryDate = users.getString("entryDate");
            if (!StringUtils.isBlank(entryDate) && !"".equals(entryDate)) {
                if ("1".equals(users.getString("jobState"))) {
                    try {
                        String userId = users.getString("id");
                        List<JSONObject> leaveDate = userleaveDao.getJSONListByCondition(" AND USER_ID=?", new Object[]{userId});
                        if (leaveDate != null && leaveDate.size() > 0) {
                            JSONObject leave = leaveDate.get(0);
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            Date startDate = null;
                            Date endDate = null;
                            startDate = simpleDateFormat.parse(entryDate);
                            endDate = simpleDateFormat.parse(leave.getString("leaveDate"));
                            Long aLong = endDate.getTime() - startDate.getTime();
                            dayNumber = (int) (aLong / (1000 * 60 * 60 * 24));
                            users.put("dayNumber", dayNumber);
                        } else {
                            users.put("dayNumber", 0);
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        Date startDate = simpleDateFormat.parse(entryDate);
                        Date nowDate = userDao.nowDate();
                        Long aLong = nowDate.getTime() - startDate.getTime();
                        dayNumber = (int) (aLong / (1000 * 60 * 60 * 24));
                        users.put("dayNumber", dayNumber);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                users.put("dayNumber", 0);
            }
            listSendData.add(users);
        }
        return listSendData;
    }

    @Override
    public String updateFileNo(String model) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(model, JSONObject.class);
        String com = jsonParams.getString("companyName");
        List<JSONObject> users = userDao.getViewJSONListByCondition(" and companyName =? ", new Object[]{com});
        UserEntity entity = new UserEntity();
        Integer rows = 0;
        for (int i = 0; i < users.size(); i++) {
            JSONObject json = users.get(i);
            String companyName = json.getString("companyName");
            companyName = companyName.replace("灜", "一");
            String companyPy = toPinyin(companyName);
            String UPcompanyPy = companyPy.toUpperCase();
            if (i < ONE_THOUSAND) {
                entity.setFileNo(UPcompanyPy + String.format("%04d", i + 1));
                entity.setId(json.getString("id"));
                rows = userDao.update(entity);
            }

        }
        return rows == 0 ? "" : entity.getId();
    }
/*
    @Override
    public List<JSONObject> getProUserList(JSONObject jsonObject) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonObject, JSONObject.class);
        List<JSONObject> result = new ArrayList<>();
        String uname = jsonParams.getString("uname");
        // System.out.println(uname);
        try {
            JSONObject resultJson = new JSONObject();
            List<IBaseEntity> list = userDao.javaInvokePro(uname);
            resultJson.put("list", list);
            result.add(resultJson);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }*/


    @Override
    public JSONObject getContacts(JSONObject jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject result = new JSONObject();
        JSONObject jobStates = new JSONObject();
        String key = jsonParams.getString("key");
        String userId = jsonParams.getString("userId");
        String companyId = jsonParams.getString("companyId");
        //对 林恩智 - 15135188260 // 马江帆  - 18636133687  // 靳悦双 -	13007090305  //郝康建	  2017121917304DF1A2D94B69CEF16770
        // 刘新华  20171219123942AAAA074F6A41D82ABF-> 的特殊处理
        if (userId.equals("20171219122040B28198B030F64B7D37")
                || userId.equals("2018012211114F47998BBAD3CEF1284A")
                || userId.equals("201712171257484DA20FEC7F96A76B3D")
                || userId.equals("2017121917304DF1A2D94B69CEF16770")
                || userId.equals("20171219123942AAAA074F6A41D82ABF")
                || userId.equals("20171219172947A5B519E1C58D66BE20")) {
            userId = "201711271733404C9DA1461F2421F828";
        }
        //特殊处理结束
        String userIds = checkDao.getChilderByUserId(userId, true);
        List<JSONObject> companys = userDao.getCompanyByUserId(userIds);
        String companyIds = "";
        if (companys != null && companys.size() > 0) {
            for (JSONObject company : companys) {
                companyIds += "'" + company.getString("id") + "',";
            }
        }
        companyIds = companyIds.substring(0, companyIds.length() - 1);
        List<Object> sqlArgs = new ArrayList<Object>();
        //模糊查询参数
        StringBuilder condition = new StringBuilder();
        if (!StringUtils.isBlank(key)) {
            condition.append(" and (name LIKE " + "'%" + key + "%'" + " "
                    + " or tel LIKE " + "'%" + key + "%'" + " )");
        }
        if (!StringUtils.isBlank(companyId)) {
            condition.append(" AND companyId ='" + companyId + "'");
        }
        condition.append(" AND companyId in (" + companyIds + ") \n");
        //查询在职状态
        //试岗
        int tryJob = userDao.getViewPageCount(condition.toString() + " and main=1 and jobState=-2 ", sqlArgs.toArray());
        //试用期
        int trialJob = userDao.getViewPageCount(condition.toString() + " and main=1 and jobState=-1 ", sqlArgs.toArray());
        //在职
        int activeJob = userDao.getViewPageCount(condition.toString() + " and main=1 and jobState=0 ", sqlArgs.toArray()); //查询出总数
        condition.append(" AND jobState!=1 \n");
        condition.append(" AND main = 1 \n");
        condition.append(" group by id \n");
        condition.append("ORDER BY companySortNo,departSortNo,companyId,departId,roleSortNo,entryDate \n");
        jobStates.put("tryJob", tryJob);
        jobStates.put("trialJob", trialJob);
        jobStates.put("activeJob", activeJob);
        result.put("jobStates", jobStates);
        List<JSONObject> list = userDao.getContacts(condition.toString());
        getRegionByUserId(list);
        result.put("records", list);
        return result;
    }

    @Override
    public List<JSONObject> getDownList(String userId) {
        String userIds = checkDao.getChilderByUserId(userId, true);
        List<JSONObject> companys = userDao.getCompanyByUserId(userIds);
        String companyIds = "";
        if (companys != null && companys.size() > 0) {
            for (JSONObject company : companys) {
                companyIds += "'" + company.getString("id") + "',";
            }
        }
        companyIds = companyIds.substring(0, companyIds.length() - 1);
        List<Object> sqlArgs = new ArrayList<Object>();
        //模糊查询参数
        StringBuilder condition = new StringBuilder();
        condition.append(" AND companyId in (" + companyIds + ") \n");
        condition.append(" AND main = 1 AND jobState!=1 ORDER BY companyId,departId,roleSortNo ");
        List<JSONObject> list = userDao.getContacts(condition.toString());
        getRegionByUserId(list);
        return list;
    }

    public List<JSONObject> getRegionByUserId(List<JSONObject> list) {
        for (int i = 0; i < list.size(); i++) {
            if ("区域经理".equals(list.get(i).getString("roleName")) || "大客户经理".equals(list.get(i).getString("roleName"))) {
                String userId = list.get(i).getString("id");
                JSONObject region = regionDao.getRegionByRoleName(userId, "AND PARENT_ID != '0'");
                if (region != null) {
                    list.get(i).put("regionName", region.getString("name"));
                }
            }
            if ("13803457171".equals(list.get(i).getString("tel"))) {
                list.remove(i);
                i--;
            }
        }
        return list;
    }


    @Override
    public Boolean RevertPinYin() {
        //插入姓名拼音
        RevertPingYinDao tool = new RevertPingYinDao();
        List<JSONObject> users = userDao.RevertPinyinUser();
        for (JSONObject user : users) {
            UserEntity model = JSON.toJavaObject(user, UserEntity.class);
            try {
                String spell = tool.toPinYin(model.getName(), "", RevertPingYinDao.Type.LOWERCASE);
                if (StringUtils.isBlank(model.getSpell()) || "".equals(model.getSpell())) {
                    model.setSpell(spell);
                    userDao.update(model);
                }

            } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
                badHanyuPinyinOutputFormatCombination.printStackTrace();
            }
        }
        return true;
    }

    @Override
    public List<JSONObject> getBackRemindUser() {
        String condition = "AND frontFlag!=1";
        String beginTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd 00:00:00");
        String endTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd 08:20:00");
        return userDao.AllUser(condition, beginTime, endTime);
    }

    @Override
    public List<JSONObject> getFrontRemindUser() {
        String condition = "AND frontFlag=1";
        String beginTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd 00:00:00");
        String endTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd 07:50:00");
        return userDao.AllUser(condition, beginTime, endTime);
    }

    @Override
    public List<JSONObject> getALLFront() {
        return userDao.getALLFront();
    }

    @Override
    public List<JSONObject> getHRUser() {
        String condition = "";
        return userDao.getHRUser(condition);
    }

    @Override
    public List<JSONObject> getCompanyUsers(String companyId, String userId) {
        return userDao.getCompanyUsers(companyId, userId);
    }

    @Override
    public List<JSONObject> getAbsenceFrontUser(String companyId) {
        String condition = " AND main=1 AND frontFlag=1 AND v_sys_user.companyId='" + companyId + "'";
        String beginTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd 00:00:00");
        String endTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd 08:40:00");
        return userDao.AllUser(condition, beginTime, endTime);
    }

    @Override
    public List<JSONObject> getAbsenceUser(String companyId) {
        String condition = " AND main=1 AND v_sys_user.companyId='" + companyId + "'";
        String beginTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd 00:00:00");
        String endTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd 08:40:00");
        return userDao.AllUser(condition, beginTime, endTime);
    }

    @Override
    public List<JSONObject> getBirthdayUsers(String date) {
        //return userDao.getBirthdayUsers(date);
        return null;
    }

    @Override
    public List<JSONObject> getUserBycondition(String condition) {
        return userDao.getViewJSONListByCondition(condition, new Object[]{});
    }

    @Override
    public Boolean MD5Util() {
        List<JSONObject> users = userDao.getViewJSONListByCondition("AND MAIN=1", new Object[]{});
        for (JSONObject object : users) {
            UserEntity entity = JSON.toJavaObject(object, UserEntity.class);
            StringBuilder sb = new StringBuilder(userDao.getMD5(entity.getPwd()));
            entity.setPwd(sb.reverse().toString());
            if (!StringUtils.isBlank(entity.getTel())) {
                userDao.update(entity);
            }
        }
        return true;
    }

    @Override
    public JSONObject MD5Crack(String jsonData) {
        JSONObject jSONObject = JSON.parseObject(jsonData);
        return userDao.MD5Crack(jSONObject);
    }

    @Override
    public JSONObject ForgetPwd(String tel) {
        List<JSONObject> listTel = userDao.getJSONListByCondition(" AND TEL=? AND JOB_STATE!=1", new Object[]{tel});
        JSONObject jsonObject = new JSONObject();
        StringBuilder yzm = userDao.ForgetPwd();
        if (listTel != null && listTel.size() > 0) {
            JSONObject user = listTel.get(0);
            String userId = user.getString("id");
            JSONObject msgObject = new JSONObject();
            jsonObject.put("userId", user.getString("id"));
            jsonObject.put("yzm", yzm);
            msgObject.put("userIds", userId);//object.getString("id")
            msgObject.put("content", String.format("OA：您的验证码为：%1s,此验证码用于修改密码。5分钟内有效,如非本人操作,请忽略。\n%2s", yzm, DateUtils.parse(new Date(), "yyyy-MM-dd HH:mm")));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
            YzmEntity yzmEntity = new YzmEntity();
            yzmEntity.setUserId(userId);
            yzmEntity.setYzm(yzm.toString());
            yzmEntity.setCreateTime(yzmDao.getCurrentTime());
            yzmDao.add(yzmEntity);
        }
        return jsonObject;
    }

    @Override
    public JSONObject reEntry(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String jobState = jsonParams.getString("jobState");
        UserEntity userEntity = null;
        JSONObject jsonObject = new JSONObject();
        if (!StringUtils.isBlank(userId) && !StringUtils.isBlank(jobState)) {
            userEntity = userDao.getById(userId);
        } else {
            jsonObject.put("result", false);
            return jsonObject;
        }
        if (null != userEntity) {
            userEntity.setJobState(Integer.parseInt(jobState));
            userDao.update(userEntity);
            userleaveDao.removeByCondition(" AND USER_ID=?", new String[]{userEntity.getId()});
            jsonObject.put("result", true);
        } else {
            jsonObject.put("result", false);
        }
        return jsonObject;
    }

    @Override
    public String yzmCheck(String yzm, String userId) {
        JSONObject msgObject = new JSONObject();
        JSONObject yzmObject = yzmDao.checkAndYzm(userId);
        if (yzmObject != null) {
            String YZM = yzmObject.getString("yzm");
            String second = yzmObject.getString("second");
            if (Integer.parseInt(second) < 300) {
                if (!StringUtils.isBlank(yzm) && yzm.equals(YZM)) {
                    return "1";// msgObject.put("flag",0);//验证成功 0
                } else {
                    return "验证码错误";
                }
            } else {
                return "验证码失效，请重新获取";
            }
        }
        return "参数错误";
    }

    @Override
    public JSONObject lzSendMessage(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        JSONObject userJson = userDao.getViewJSONListByCondition(" AND id = ? AND main = 1 ", new Object[]{userId}).get(0);
        String roleName = userJson.get("roleName").toString();
        String name = userJson.get("name").toString();
        List<JSONObject> data = userDao.getDataLength(userId);//
        String yszyId = "2018072410074E31BDA9D2DDCC10562B";//应收专员袁一鸣
        if (data.size() > 0) {
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", yszyId);
            msgObject.put("content", String.format(RESIGNATION_YSTZ_MESSAGE2,
                    roleName,
                    name));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
        }
        JSONObject object = new JSONObject();
        object.put("records", "发送成功");
        return object;
    }

    @Override
    public String updateAllUsersArchivaType() {
        List<UserEntity> users = userDao.getEntityListByCondition("AND TEL != '' ", new Object[]{});
        for (int i = 0; i < users.size(); i++) {
            UserEntity model = users.get(i);
            if (StringUtils.isBlank(String.valueOf(model.getSex()))
                    || StringUtils.isBlank(model.getName())
                    || StringUtils.isBlank(model.getTel())
                    || StringUtils.isBlank(model.getEntryDate())
                    || StringUtils.isBlank(String.valueOf(model.getJobState()))
                    || StringUtils.isBlank(model.getBirthday())
                    || StringUtils.isBlank(model.getNativePlace())
                    || StringUtils.isBlank(model.getPermanent())
                    || StringUtils.isBlank(model.getCard())
                    || StringUtils.isBlank(model.getCardAttachName())
                    || StringUtils.isBlank(model.getAddress())
                    || StringUtils.isBlank(model.getGraduate())
                    || StringUtils.isBlank(model.getEducation())
                    || StringUtils.isBlank(model.getProfessional())
                    || StringUtils.isBlank(model.getEntrtyInforAttachName())
                    || StringUtils.isBlank(model.getEntrtyAgreeAttachName())
                    || StringUtils.isBlank(model.getContractAttachName())
                    || StringUtils.isBlank(model.getSecrecyAttachName())
                    || StringUtils.isBlank(model.getWegeCard())
                    || StringUtils.isBlank(model.getBank())
                    || StringUtils.isBlank(model.getTelOwner())
                    || StringUtils.isBlank(String.valueOf(model.getComputerStart()))
                    || StringUtils.isBlank(model.getComputerOwner())
                    || StringUtils.isBlank(String.valueOf(model.getCarStart()))
                    || (!String.valueOf(model.getCarStart()).equals("0") && StringUtils.isBlank(model.getCarAttachName()))
                    || (!String.valueOf(model.getCarStart()).equals("0") && StringUtils.isBlank(model.getCarCard()))
                    || StringUtils.isBlank(model.getEmail())
                    ) {
                model.setArchivaType(0);
            } else {
                model.setArchivaType(1);
            }
            userDao.update(model);
        }
        return "更新成功";
    }
}
